import 'dart:async';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/leave_msg_entity.dart';
import 'package:factoryside/bean/policy_entity.dart';
import 'package:factoryside/eventbus/global_eventbus.dart';
import 'package:factoryside/generated/json/policy_entity_helper.dart';
import 'package:factoryside/service/order_service.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/FadeRoute.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/grid_images_view.dart';
import 'package:factoryside/widget/page_photo_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:http_parser/http_parser.dart';
///工单留言
class LeaveMsgPage extends StatefulWidget{

  int orderid;

  LeaveMsgPage(this.orderid);

  @override
  State<StatefulWidget> createState() {
    return LeaveMsgPageState();
  }
}

class LeaveMsgPageState extends State<LeaveMsgPage>{

  List<LeaveMsgDataData> list;
  TextEditingController msgCon=TextEditingController();
  ImagesGridviewWidget imagesGridviewWidget;

  ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();
    imagesGridviewWidget = ImagesGridviewWidget(5);
//    OrderService.appLeavemessage(widget.orderid).then((value){
//      if(value.data.code==0){
//        setState(() {
//          list=value.data.data;
//          if(list.length>0){
//            Timer(Duration(milliseconds: 100), () {
//              //List滑动到底部
//              _controller.jumpTo(_controller.position.maxScrollExtent);
//            });
//          }
//        });
//      }else{
//        showToast( value.data.msg);
//      }
//    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:buildAppBar('工单留言',null,context),
      //未获取到数据就居中显示加载图标
      body: buildBody(context),
    );
  }

  Widget buildBody(BuildContext context){
    return ListView(
      children: [
        /*输入框*/
        Container(
            margin: EdgeInsets.only(
                top: 10, bottom: 0, left: 10, right: 10),
            padding: EdgeInsets.only(bottom: 5, left: 10, right: 10),
            width: double.infinity,
            decoration: BoxDecoration(
                color: Color.fromARGB(180, 240, 240, 240),
                border: Border.all(width: 0.2, color: Colors.grey),
                borderRadius: BorderRadius.all(Radius.circular(3))),
            child: TextField(
              controller: msgCon,
              style: TextStyle(fontSize: 13, color: Colors.black),
              maxLines: 4,
//              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                hintText: '请输入留言',
                counterText: '',
                disabledBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
              ),
            )),
        Container(
          padding: EdgeInsets.all(10),
          child: imagesGridviewWidget,
        ),
        Container(
          color: Colors.transparent,
          width: double.infinity,
          height: 50,
          margin: EdgeInsets.all(10),
          child: RaisedButton(
            onPressed: () {
              if(isFastClick())return;//防重复点击
              List<String> images=List();
              if(imagesGridviewWidget.images.length==0){
                if (msgCon.text.isEmpty) {
                  showToast( '内容不能为空');
                  return;
                }
                RequestUtil.post(Api.addLeaveMessageForOrder,
                    {'OrderId':'${widget.orderid}',
                      'UserId': Api.userName,
                      'Type': 2,
                      'factoryIslook': 2,
                      'Content': msgCon.text,
                      'photo': ''}
                ).then((value) => this.setState(() {
                  if(value['Data']['Item1']){
                    GlobalEventBus().eventBus.fire(StateChangeEvent('工单留言'));
                    Navigator.pop(context,true);
                  }
                  showToast(value['Data']['Item2']);
                }));
              }else{
//                OrderService.getPolicyToken().then((value) {
                  images.clear();
                  RequestUtil.showLoadingDialog(context);
                  imagesGridviewWidget.images.forEach((element) async {
                    RequestUtil.post(Api.getPolicyToken, {}).then((value) async {
                      var policy=policyDataFromJson(PolicyData(), value['Data']);
                      String objkey =
                          'TemporaryArea/APP/LeaveMsg/${widget.orderid}/${element.uuid}.jpg';
                      // 获取 ByteData
//                      ByteData byteData = await element.asset.getByteData(quality: Api.quality);
//                      List imageData = byteData.buffer.asUint8List();
                      List imageData = await FlutterImageCompress.compressWithFile(element.asset,quality: Api.quality);
                      MultipartFile multipartFile = MultipartFile.fromBytes(
                        imageData,
                        // 文件名
                        filename: objkey,
                        // 文件类型
                        contentType: MediaType("image", "jpg"),
                      );
                      //表单需要的参数: AccessKeyId、AccessKeySecret、SecurityToken;
                      FormData formdata = new FormData.fromMap({
                        //文件名，随意
                        'photo': objkey,
                        //"可以填写文件夹名（对应于oss服务中的文件夹）/" + fileName
                        'key': objkey, //上传后的文件名
                        'policy': policy.policy,
                        //Bucket 拥有者的AccessKeyId。
                        'OSSAccessKeyId': policy.accessid,
                        //让服务端返回200，不然，默认会返回204
                        'success_action_status': '200',
                        'Signature': policy.signature,
                        'file': multipartFile
                        //必须放在参数最后
                      });
                      //然后通过存储地址直接把表单(formdata)上传上去;
                      Dio dio = Dio();
                      dio.options.responseType = ResponseType.plain;
                      var response =
                          await dio.post(policy.host, data:formdata);
                      print(response);
                      if (response.statusCode == 200) {
                        print(policy.host + objkey);
                        images.add(policy.host + objkey);
                        if (images.length == imagesGridviewWidget.images.length) {
                          var photo = '';
                          for (int i = 0; i < images.length; i++) {
                            photo += images[i]+',';
                          }
                          if (photo.contains(',')) {
                            photo = photo.substring(0, photo.lastIndexOf(','));
                          }
                          RequestUtil.post(Api.addLeaveMessageForOrder,
                              {'OrderId':'${widget.orderid}',
                               'UserId': Api.userName,
                               'Type': 2,
                               'factoryIslook': 2,
                               'Content': msgCon.text,
                               'photo': photo}
                          ).then((value) => this.setState(() {
                            if(value['Data']['Item1']){
                              GlobalEventBus().eventBus.fire(StateChangeEvent('工单留言'));
                              RequestUtil.hiddenLoadingDialog(context);
                              Navigator.pop(context,true);
                            }
                            showToast( value['Data']['Item2']);
                          }));
                        }
                      }else{
                        showToast('上传失败，请重试。');
                        RequestUtil.hiddenLoadingDialog(context);
                      }
                    });
                  });

//                });
              }
            },
            child: Text(
              '提交',
              style: TextStyle(color: Colors.white),
            ),
            color: ColorsUtil.hexToColor(Api.btnColor),
          ),
        )
      ],
    );
  }
  Widget buildEmptyContainer() {
    return Expanded(child: Container(
      color: Colors.white,
      child: ListView(
        children: [
          Container(
            height: 500,
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    'assets/v3_nodata.png',
                    width: 100,
                    height: 100,
                  ),
                  Text(
                    '暂无留言',
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ));
  }
  Widget buildListView(BuildContext context, List<LeaveMsgDataData> list){
    return Expanded(
      child: Container(
        color: Colors.white,
        child: ListView.builder(
          //想设置item为固定高度可以设置这个，不过文本过长就显示不全了
//            itemExtent: 100,
        controller: _controller,
            itemCount: list == null ? 0 : list.length,
            itemBuilder: (BuildContext context, int position){
              return buildListViewItem(context, list, position);
            }
        ),
      ),
    );
  }

  Widget buildListViewItem(BuildContext context, List<LeaveMsgDataData> list, int position){
    if(list.length != 0){
      return Container(
        color: Colors.white,
        padding: EdgeInsets.only(left: 20, right: 10),
        child: IntrinsicHeight(child: Row(
          children: [
            //这个Container描绘左侧的线和圆点
            Container(
              margin: EdgeInsets.only(left: 10),
              width: 20,
              //需要根据文本内容调整高度，不然文本太长会撑开Container，导致线会断开
//              height: getHeight(list[position].content),
              child: Column(
                //中心对齐，
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                      flex: 1,
                      child: Container(
                        //第一个item圆点上方的线就不显示了
                        width: position == 0 ? 0 : 1,
                        color: Colors.grey.shade300,
                      )
                  ),
                  //第一个item显示稍大一点的绿色圆点
                  position == 0 ? Stack(
                    //圆心对齐（也就是中心对齐）
                    alignment: Alignment.center,
                    children: <Widget>[
                      //为了实现类似阴影的圆点
                      Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                          color: Colors.blue.shade200,
                          borderRadius: BorderRadius.all(Radius.circular(10)),
                        ),
                      ),
                      Container(
                        height: 14,
                        width: 14,
                        decoration: BoxDecoration(
                          color: Colors.blue,
                          borderRadius: BorderRadius.all(Radius.circular(7)),
                        ),
                      ),
                    ],
                  ) : Container(
                    height: 10,
                    width: 10,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade300,
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                    ),
                  ),
                  Expanded(
                      flex: 1,
                      child: Container(
                        width: position == list.length-1 ? 0 : 1,
                        color: Colors.grey.shade300,
                      )
                  ),
                ],
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                  Text(
                    list[position].content,
                    style: TextStyle(
                      fontSize: 15,
                      //第一个item字体颜色为绿色+稍微加粗
                      color: position == 0 ? Colors.blue : Colors.black,
                      fontWeight: position == 0 ? FontWeight.w600 : null,
                    ),
                  ),
                    SizedBox(
                      height: 5,
                    ),
                    Wrap(
                      children: list[position].imgUrls
                          .asMap()
                          .keys
                          .map((index) => buildGestureDetector_img(
                          index, list[position].imgUrls))
                          .toList(),
                    ),
                    SizedBox(
                      height: 5,
                    ),
                  Text(
                    list[position].createDate,
                    style: TextStyle(
                      fontSize: 15,
                      //第一个item字体颜色为绿色+稍微加粗
                      color: position == 0 ? Colors.blue : Colors.grey,
                      fontWeight: position == 0 ? FontWeight.w600 : null,
                    ),
                  ),
                    SizedBox(
                      height: 5,
                    ),
                  Text(
                    list[position].userName,
                    style: TextStyle(
                      fontSize: 15,
                      //第一个item字体颜色为绿色+稍微加粗
                      color: position == 0 ? Colors.blue : Colors.black,
                      fontWeight: position == 0 ? FontWeight.w600 : FontWeight.bold,
                    ),
                  ),

                ],),
              ),
            ),
          ],
        ),),
      );
    }else{
      return Container();
    }
  }
  GestureDetector buildGestureDetector_img(int index, List<String> urls) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(right: 5),
        child: CachedNetworkImage(
          imageUrl:urls[index],
          width: 40,
          height: 40,
          fit: BoxFit.fill,
        ),
      ),
      onTap: () {
        //FadeRoute是自定义的切换过度动画（渐隐渐现） 如果不需要 可以使用默认的MaterialPageRoute
        Navigator.of(context).push(FadeRoute(
            page: PhotoViewGalleryScreen(
              images: urls, //传入图片list
              index: index, //传入当前点击的图片的index
              heroTag: '', //传入当前点击的图片的hero tag （可选）
            )));
      },
    );
  }

  Widget showLoading(){
    return Center(
      child: CircularProgressIndicator(),
    );
  }

}
